import React from 'react';
import styled from 'styled-components';
import md5 from 'js-md5';
import jsencrypt from 'jsencrypt';
import LinearGradient from 'react-native-linear-gradient';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import { KeyboardAvoidingView, ScrollView, Dimensions } from 'react-native';
import { login, fetchUserInfo } from '../../api';
import { saveToken, getToken, saveUserInfo } from '../../utils/auth';
import { saveUserInfoAction } from '../../redux/actions';
import Toast from 'antd-mobile-rn/lib/toast';

// 单独引入组件
import InputItem from 'antd-mobile-rn/lib/input-item';
import WhiteSpace from 'antd-mobile-rn/lib/white-space';

class Login extends React.Component {
  state = {
    screenHeight: Dimensions.get('window').height,
    username_error: false,
    password_error: false,
    username: '',
    password: ''
  };

  encrypt = userInfo => {
    const encrypt = new jsencrypt();
    encrypt.setPublicKey(
      'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXG6PqVQsShQGqWrLeX1fbCqyz9KKUn7OjoLfOc2UxKu5+134kxI41j7VP8rV1u6kr4hSCaKiiJk5aziBYDPRtHlWYAfK9Rfj1j6uKzdW8hcl368EbEaw+k/vT6bCf4NSLYzxFY6Lzk9NtskMCVfX8159KE3bWnylrKuOpexbyfQIDAQAB'
    );
    const encrypted = encrypt.encrypt(userInfo);
    return encrypted;
  };

  login = () => {
    // Actions.home(); // 跳转
    let { username, password } = this.state;
    if (username === '') {
      Toast.info('用户名不能为空!', 1);
      this.setState({
        username_error: true
      });
      return;
    }
    if (password === '' && password.length < 6) {
      Toast.info('密码不能为空!', 1);
      this.setState({
        password_error: true
      });
      return;
    }

    const md5Password = md5(password);
    const userInfo = { userName: username, password: md5Password };

    const encrypted = this.encrypt(JSON.stringify(userInfo));

    login(encrypted)
      .then(res => {
        if (res.code === '0') {
          saveToken(res.data.token);

          // Save user information in Redux State
          fetchUserInfo(res.data.token).then(info => {
            if (info.code === '0') {
              console.log('用户信息', JSON.stringify(info, 0, 4));
              this.props.saveUserInfo(info.data);
              saveUserInfo(info.data);
              Actions.home();
            }
          });
        } else {
          Toast.info(res.msg, 1);
        }
      })
      .catch(err => {
        console.log('登陆异常：', err);
      });
  };

  componentDidMount() {
    getToken().then(token => {
      console.log('login page componentDidMount token', token);
      if (token) {
        // Actions.home();
      }
    });
  }

  render() {
    return (
      <KeyboardAvoidingView>
        <ScrollView
          contentContainerStyle={{
            height: this.state.screenHeight
          }}>
          <Container>
            <HeaderLogo>
              <Image source={require('../../assets/login/bj.png')} />
            </HeaderLogo>
            <AppTitle>
              <Logo source={require('../../assets/login/LOGO.png')} />
              <Title source={require('../../assets/login/title.png')} />
            </AppTitle>
            <Form>
              <UserInputItem
                placeholder="用户名/账号/手机号"
                error={this.state.username_error}
                onChange={val =>
                  this.setState({
                    username: val,
                    username_error: false
                  })
                }>
                <AccountLogo
                  source={require('../../assets/login/user_logo.png')}
                />
              </UserInputItem>

              <WhiteSpace size="md" />

              <UserInputItem
                placeholder="请输入您的密码"
                type="password"
                error={this.state.password_error}
                onChange={val =>
                  this.setState({
                    password: val,
                    username_error: false
                  })
                }>
                <AccountLogo
                  source={require('../../assets/login/lock_logo.png')}
                />
              </UserInputItem>

              <WhiteSpace size="md" />

              <CustomLinearGradient
                colors={['#51B6FC', '#7666FE']}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}>
                <MyTouchableOpacity onPress={() => this.login()}>
                  <LoginText>登录</LoginText>
                </MyTouchableOpacity>
              </CustomLinearGradient>
            </Form>
          </Container>
        </ScrollView>
      </KeyboardAvoidingView>
    );
  }
}

const mapDispatchToProps = dispatch => {
  return {
    saveUserInfo: data => {
      dispatch(saveUserInfoAction(data));
    }
  };
};

export default connect(
  null,
  mapDispatchToProps
)(Login);

const Container = styled.View`
  width: 100%;
  height: 100%;
  background: white;
`;

const HeaderLogo = styled.View`
  background: white;
  width: 100%;
  height: 268.8;
`;

const AppTitle = styled.View`
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin-top: 28.67;
`;
const Logo = styled.Image`
  width: 26.67;
  height: 26.67;
  margin-right: 11;
`;
const Title = styled.Image`
  width: 71.33;
  height: 23;
`;

const Image = styled.Image`
  width: 100%;
  height: 100%;
`;

const Form = styled.View`
  background: white;
  margin-top: 51;
  justify-content: center;
  align-items: center;
`;

const UserInputItem = styled(InputItem)`
  background: #f8f8f8;
  width: 317.67;
`;

const AccountLogo = styled.Image`
  margin-left: 30;
`;

const LoginText = styled.Text`
  color: white;
  font-size: 15.94;
`;

const MyTouchableOpacity = styled.TouchableOpacity`
  width: 317.67;
  height: 42.17;
  justify-content: center;
  align-items: center;
`;

const CustomLinearGradient = styled(LinearGradient)`
  margin-left: 14;
  margin-top: 18.67;
  border-radius: 3.33;
`;
